var createError = require('http-errors');
var express = require('express');
var path = require('path');
//cookie模块
var cookieParser = require('cookie-parser');
//默认日志
var logger = require('morgan');
//引入路由集合
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
//自定义中间件 允许跨域  或者使用core
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});
app.use(logger('dev'));
//解析 JSON 格式的请求体数据
app.use(express.json());
//解析 URL-encoded 格式的请求体数据
//解析表单中的 url-encoded 格式的数据
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//是否开启静态文件的虚拟路径
//快速托管静态资源的内置中间件
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/zjq',express.static(path.join(__dirname, 'public')));
//路由虚拟路径 注册路由
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
